package com.atguigu.myjuc.demo;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 锁降级
 */
public class LockDowngradingDemo {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public int data = 0;
    public int readData(){
        /*rwLock.readLock().lock();
        try {
            return data;
        }finally {
            rwLock.readLock().unlock();
        }*/
        rwLock.readLock().lock();
        try {
           return data;
        }finally {
            rwLock.readLock().unlock();
        }
    }

    public void updateData(int newData){
        /*rwLock.writeLock().lock();
        try {
            data =newData;
            System.out.println("开始写入"+ newData);
            rwLock.readLock().lock();
            System.out.println("锁降级");
        }finally {
            rwLock.writeLock().unlock();
        }
        try {
            int currenData = readData();
            System.out.println("降级读取" + currenData);
        } finally {
            rwLock.readLock().unlock();
        }*/
        rwLock.writeLock().lock();
        try {
            data = newData;
            System.out.println("开始写入"+newData);
            rwLock.readLock().lock();
            System.out.println("锁降级");
        }finally {
            rwLock.writeLock().unlock();
        }
        try {
            int currentData = readData();
            System.out.println("锁降级读信息"+currentData);
        }finally {
            rwLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        /*LockDowngradingDemo example = new LockDowngradingDemo();
        new Thread(()->{
            example.updateData(100);
        }).start();

        new Thread(()->{
            int currentData = example.readData();
            System.out.println("线程读"+ currentData);
        }).start();*/
        LockDowngradingDemo demo = new LockDowngradingDemo();
        new Thread(()->{
            demo.updateData(100);
        }).start();

        new Thread(()->{
            int currentData = demo.readData();
            System.out.println("线程读数据"+ currentData);
        }).start();

    }
}
